package com.situ.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.situ.util.JDBCUtil;


@WebServlet("/deleteStudent")
public class StudentDeleteServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 拿到要删除的id
		// http://localhost:8080/JavaWeb/deleteStudent?id=6
		// 从浏览器拿到的数据都是字符串，即使id=6写的是数字，也是以字符串形式得到
		String id = req.getParameter("id");
		
		Connection connection = null;
		PreparedStatement statement = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "delete from student where id=?";
			statement = connection.prepareStatement(sql);
			// Integer.parseInt() 把一个字符串类型的数字解析成整数
			statement.setInt(1, Integer.parseInt(id));
			int count = statement.executeUpdate();
			System.out.println(statement);
			System.out.println("count: " + count);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, statement, null);
		}
		
		// 重定向到展示所有的列表界面 /JavaWeb/student
		resp.sendRedirect(req.getContextPath() + "/student");
	}
}
